<?php
declare (strict_types=1);

namespace app\middleware;

use app\server\Redis;

class CheckLogin {
    /**
     * 仅验证登录
     * @param $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next) {
        try {
            $token = trim(ltrim($request->header('Authentication'), 'Bearer'))??'';
        }catch (\Exception $e){
            return error('登录状态失效，请重新登录',401);
        }

        if ($token) {
            //验证登录
            $master_info = verifyJwt($token);//token验证
            if ($master_info['code'] == 0) {
                return error($master_info['msg'],401);
            }
            $redis = new Redis();
            $master = $redis->getToken($master_info['data']['uid']);
            if (empty($master)) {
                return error('登录状态失效，请重新登录',401);
            }
            if ($master_info['data']['status'] != 1) {
                return error('账号被禁用');
            }
            $master_info['data']['ws_url']="ws://".GetHostByName($_SERVER['SERVER_NAME']).":9151";
            $request->master = $master_info['data'];
        } else {
            return error('登录信息失效，请重新登录',401);
        }
        return $next($request);
    }
}
